//
// Unihan Input Method
//
// Copyright © 2002-2007 Sun Wah Linux Ltd.
//
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
// USA
//
// $Id: utils.c 757 2007-05-10 08:19:31Z roger $
//

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include "utils.h"
#include "const.h"

#define BUFFER_SIZE 1024


char *
get_home_dir()
{
	return getenv("HOME");
}

void
filecp(const char *dest, const char *orig)
{
		 
	int from_fd,to_fd;
	int bytes_read,bytes_write;
	char buffer[BUFFER_SIZE];
	char *ptr;

	if((from_fd=open(orig, O_RDONLY)) == -1) {
		fprintf(stderr,"Open %s Error:%s\n", orig, strerror(errno));
		return;
	}
	
	if((to_fd=open(dest, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1) {
		fprintf(stderr,"Open %s Error:%s\n", dest, strerror(errno));
		return;
	}
	
	while(bytes_read = read(from_fd, buffer, BUFFER_SIZE)) {
		if((bytes_read == -1) && (errno != EINTR))
			break;
		else if(bytes_read > 0) {
			ptr=buffer;
			while(bytes_write = write(to_fd, ptr, bytes_read)) {
				if((bytes_write == -1) && (errno != EINTR))
					break;
				else if(bytes_write == bytes_read)
					break;
				else if(bytes_write > 0) {
					ptr += bytes_write;
					bytes_read -= bytes_write;
				}
			}
			if(bytes_write == -1)
				break;
		}
	}
	close(from_fd);
	close(to_fd);
	return;
}

const unsigned char *
utf8_next_char(const unsigned char *in)
{
	if (*in < 128)
		return (in + 1);
	else if ((*in & 0xE0) == 0xC0)
		return (in + 2);
	else if ((*in & 0xF0) == 0xE0)
		return (in + 3);
	else if ((*in & 0xF8) == 0xF0)
		return (in + 4);
	else if ((*in & 0xFC) == 0xF8)
		return (in + 5);
	else if ((*in & 0xFE) == 0xFC)
		return (in + 6);

	// invalid!
	return NULL;
}

int
utf8_charlen(const unsigned char *in)
{
        int len = 0;

        while (*in) {
                ++len;
                in = utf8_next_char(in);
        }
        return len;
}


// vi:ts=4:nowrap:cin:expandtab
